package com.hanshg.cherry.controller.file;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hanshg.cherry.base.result.Results;
import com.hanshg.cherry.dto.OssObjectDto;
import com.hanshg.cherry.service.aliyun.AliYunOssService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 文件上传控制器
 *
 * @author 柠檬水
 * @date 2020/04/13
 */
@Controller
@RequestMapping("fileUpload")
@Slf4j
@Api(tags = "文件处理工具层")
public class FileUploadController {

    @Autowired
    private AliYunOssService aliYunOssService;

    /**
     * @author 柠檬水
     * @desc 文件上传到oss
     * @return FileUploadResult
     * @Param uploadFile
     */
    @PostMapping(value = "/upload")
    @ResponseBody
    public JSONObject headImg(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request) throws Exception {
        log.info("上传了文件："+file.getOriginalFilename());
        //上传文件处理
        return aliYunOssService.updateHomeImage(file);
    }

    /**
     * @return FileUploadResult
     * @desc 根据文件名删除oss上的文件
     * @author 柠檬水
     * @Param objectName
     */
    @PostMapping("/delete")
    @PreAuthorize("hasAuthority('sys:server:del')")
    @ResponseBody
    public JSONObject delete(@RequestParam("fileName") String fileName) {
        //json转list
        List<String> array = JSON.parseArray(fileName, String.class);
        return this.aliYunOssService.deleteFile(array);
    }

    /**
     * @author 柠檬水
     * @desc 查询oss上的所有文件
     * @return List<OSSObjectSummary>
     * @Param
     */
    @RequestMapping("/list")
    @PreAuthorize("hasAuthority('sys:server:query')")
    @ResponseBody
    public Results<OssObjectDto> list() {
        Results<OssObjectDto> summaryResults = this.aliYunOssService.fileList();
        return summaryResults;
    }

    /**
     * @author 柠檬水
     * @desc 根据文件名下载oss上的文件
     * @return
     * @Param objectName
     */
    @GetMapping("/download")
    @ResponseBody
    public void download(@RequestParam("fileName") String objectName, HttpServletResponse response) throws IOException {
        /**
         * 通知浏览器以附件形式下载
         */
        log.info("下载了文件："+objectName);
        response.setHeader("Content-Disposition","attachment;filename=" + new String(objectName.getBytes(), "UTF-8"));
        this.aliYunOssService.exportOssFile(response.getOutputStream(),objectName);
    }
}
